const CLEAR_LINE_WIDTH = 40;
const { ccclass, property, requireComponent } = cc._decorator;

@ccclass
// @requireComponent(cc.Sprite)
export default class WaterDropComp extends cc.Component {




    @property(cc.Mask)
    mask: any = null;

    private mg: cc.Graphics = null;
    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}
    private tempDrawPoints: cc.Vec2[][] = [];

    @property(cc.Sprite)
    sprite: cc.Sprite = null;

    private startFlow: boolean = false;

    //流体可移动的长度，可以根据流体的粘稠度决定
    private length: number = 50;
    private tempLength: number[] = []
    private texture:cc.Texture2D = null;
    start() {
        this.mask.inverted = false;
        this.mg = this.mask._graphics;
        this.reset();
        if(this.sprite){
            this.texture = this.sprite.spriteFrame.getTexture();
        }
    }

    setTextureData(data, format, width, height) {
        if (this.texture) {
            this.texture.initWithData(data, format, width, height)
        }

    }

    setWaterLength(len: number) {
        this.length = len;
    }

    setFlow(flag: boolean) {
        this.startFlow = flag;
    }



    clearMask(pos, index: number = 0) {
        // pos = this.node.convertToNodeSpaceAR(pos)
        let stencil = this.mg
        let list = this.tempDrawPoints[index]
        if (!list) {
            list = []
            this.tempDrawPoints.push(list)
            this.tempLength[index] = 0
        }
        list.push(pos);
        // cc.log(' clearMask ======================  ',pos.x, pos.y)
        stencil.circle(pos.x, pos.y, CLEAR_LINE_WIDTH / 2);
        stencil.fill();
    }


    swap() {
        this.mask.inverted = this.mask.inverted ? false : true
    }



    reset() {
        this.mg.clear();
        this.tempDrawPoints = [];
        this.tempLength = []
    }



    update(dt) {
        if (this.startFlow) {
            for (let index = 0; index < this.tempDrawPoints.length; index++) {
                const list = this.tempDrawPoints[index];
                if (list.length > 0) {
                    if (this.tempLength[index] < this.length) {
                        let pos = list[list.length - 1]
                        if (pos.y > -this.node.height / 2) {
                            let newpos = cc.v2(pos.x, pos.y - 3)
                            this.tempLength[index] += 3
                            this.clearMask(newpos, index);
                        }
                    }

                }
            }



        }
    }
}
